<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form 
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="图片路径" prop="picUrl">
        <!-- <el-input v-model="dataForm.picUrl" placeholder="图片路径"></el-input> -->
        <el-upload
          :before-upload="beforeUploadHandle"
          :on-success="successHandle"
          :headers="uploadHeader"
          class="upload-demo"
          drag
          :action="uploadUrl"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="dataForm.description" placeholder="描述"></el-input>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime" style="display:none">
        <el-input
          v-model="dataForm.createTime"
          placeholder="创建时间"
        ></el-input>
      </el-form-item>

      <el-form-item label="截止时间" prop="showTime">
        <span class="demonstration"></span>
        <el-date-picker
          style="width: 55%"
          v-model="dataForm.showTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始展示日期"
          end-placeholder="结束展示日期"
          :picker-options="pickerOptions"
          @change="dataSearch" value-format="yyyy-MM-dd HH:mm"
          format="yyyy-MM-dd HH:mm"
        >
          >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="排序" prop="num">
        <el-input v-model="dataForm.num" placeholder="排序"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Vue from "vue";
export default {
  data() {
    return {
      uploadHeader: {
        token: Vue.cookie.get("token"), //发送的请求携带token
      },
      uploadUrl: "http://localhost:9701/mains/api/sys/oss/upload",
      visible: false,
      num: 0,
      successNum: 0,
      fileList: [],
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() < Date.now() - 1000 * 3600 * 24 * 1
            // time.getTime() > Date.now()
          );
        },
      },
      dataForm: {
        id: 0,
        picUrl: "",
        description: "",
        createTime: "",
        showTime: [],
        num: "",
      },
      dataRule: {
        picUrl: [
          // { required: true, message: "图片路径不能为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "描述不能为空", trigger: "blur" },
        ],
        createTime: [
          // { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        showTime: [
          { required: true, message: "展示时间不能为空", trigger: "blur" },
        ],
        num: [{ required: true, message: "排序不能为空", trigger: "blur" }],
      },
    };
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/homes/homepicture/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.picUrl = data.homePicture.picUrl;
              this.dataForm.description = data.homePicture.description;
              this.dataForm.createTime = data.homePicture.createTime;
              this.dataForm.showTime = data.homePicture.showTime;
              this.dataForm.num = data.homePicture.num;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/homes/homepicture/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              picUrl: this.dataForm.picUrl,
              description: this.dataForm.description,
              createTime: this.dataForm.createTime,
              showTime: this.dataForm.showTime[1],
              num: this.dataForm.num,
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },

    // 上传之前
    beforeUploadHandle(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error("只支持jpg、png、gif格式的图片！");
        return false;
      }
      this.num++;
    },
    // 上传成功
    successHandle(response, file, fileList) {
      this.fileList = fileList;
      this.successNum++;
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.dataForm.picUrl = response.url;
          this.$confirm("操作成功, 是否继续操作?", "提示", {
            confirmButtonText: "确定",
            // cancelButtonText: "取消",
            type: "warning",
          }).catch(() => {
            this.visible = false;
          });
        }
      } else {
        this.$message.error(response.msg);
      }
    },
    // 弹窗关闭时
    closeHandle() {
      this.fileList = [];
      this.$emit("refreshDataList");
    },
  },
};
</script>
